package com.shxy.service.impl;

import com.shxy.common.enums.RoleCode;
import com.shxy.controller.ui.UserInfo;
import com.shxy.dao.base.StudentDao;
import com.shxy.dao.security.UserDao;
import com.shxy.entity.custom.CustomStudent;
import com.shxy.entity.security.CustomUser;
import com.shxy.service.ISecurityService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 安全管理服务
 */
@Service
@Log
public class SecurityService implements ISecurityService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public int initStudents(String grade) {
        // 1、查询指定年级的学生
        List<CustomStudent> students = studentDao.findAllByClazzYear(grade);
        if(students.size() == 0) {
            return 0;
        }
        // 2、获取学生学号
        List<String> codes = students.stream().map(CustomStudent::getCode).collect(Collectors.toList());
        // 3、删除这些学号的学生
        userDao.deleteByRoleCodeAndUserIdIn(RoleCode.STUDENT, codes);

        List<CustomUser> passwords = new ArrayList<>();
        // 4、初始化这些学生
        students.stream().forEach(student -> {
            // 构建密码对象
            CustomUser pwd = new CustomUser();
            pwd.setRoleCode(RoleCode.STUDENT);
            pwd.setUserId(student.getCode());
            String pwdStr = student.getIdCard().isBlank() ? "123456" : student.getIdCard();
            pwd.setPwd(passwordEncoder.encode(pwdStr));
            pwd.setName(student.getName());
            passwords.add(pwd);
        });
        return userDao.saveAll(passwords).size();
    }

    @Override
    public Optional<CustomUser> checkLogin(String name, String password, int role) {
        // 1、判断账号存不存在
        RoleCode roleCode = RoleCode.getByCode(role);
        String userId = getUserId(roleCode, name);
        if(userId.isBlank()){
            return Optional.empty();
        }

        // 2、判断密码存不存在
        Optional<CustomUser> pwd = userDao.findByUserIdAndRoleCode(userId, roleCode);
        if(pwd.isEmpty()) {
            return Optional.empty();
        }

        // 3、判断密码正不正确
        // 在进行判断时，必须使用matches方法进行判断
        if(passwordEncoder.matches(password, pwd.get().getCode())) {
            return Optional.empty();
        }

        return pwd;
    }

    @Override
    public Optional<UserInfo> getUserInfoByCode(String code) {
        Optional<CustomUser> password = userDao.findByCode(code);
        if(password.isEmpty()) {
            return Optional.empty();
        }

        switch (password.get().getRoleCode()) {
            case STUDENT:
                Optional<CustomStudent> stu = studentDao.findByCode(password.get().getUserId());
                if(stu.isPresent()){
                    UserInfo u = new UserInfo();
                    u.setName(stu.get().getName());
                    u.setIntroduction("学生");
                    u.setAvatar("无");
                    u.setRoles(Arrays.asList(RoleCode.STUDENT.getName()));
                    return Optional.of(u);
                }
                break;
        }
        return Optional.empty();
    }

    @Override
    public Optional<CustomUser> getUserByCode(String code) {
        return userDao.findByCode(code);
    }

    /**
     * 判断角色和账号是否存在
     * @param roleCode
     * @param name
     * @return
     */
    private String getUserId(RoleCode roleCode, String name) {
        String userId = "";
        switch(roleCode) {
            case STUDENT:
                Optional<CustomStudent> stu = studentDao.findByCode(name);
                if(stu.isPresent()) {
                    return stu.get().getCode();
                }
                break;
        }
        return userId;
    }


}
